package com.mentalhealthplatform.teacherV2.controller;

import com.mentalhealthplatform.teacherV2.dto.StudentDTO;
import com.mentalhealthplatform.teacherV2.service.StudentFamilyServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/v2/students")
@CrossOrigin(origins = "http://localhost:3000")
public class StudentControllerV2 {

    @Autowired
    private StudentFamilyServiceV2 studentFamilyServiceV2;

    // 获取所有学生信息
    @GetMapping
    public ResponseEntity<List<StudentDTO>> getAllStudents() {
        List<StudentDTO> students = studentFamilyServiceV2.findAll();
        return ResponseEntity.ok(students);
    }

    // 根据ID获取特定学生信息
    @GetMapping("/{id}")
    public ResponseEntity<StudentDTO> getStudentById(@PathVariable UUID id) {
        Optional<StudentDTO> studentDTO = studentFamilyServiceV2.findById(id).map(StudentDTO::convertToDTO);
        return studentDTO.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 根据姓名或学号搜索学生
    @GetMapping("/searchByNameOrNumber")
    public ResponseEntity<List<StudentDTO>> getStudentsByNameOrNumber(@RequestParam String keyword) {
        List<StudentDTO> students = studentFamilyServiceV2.searchByUsernameOrNumber(keyword);
        return ResponseEntity.ok(students);
    }

    // 根据多个条件搜索学生
    @GetMapping("/search")
    public ResponseEntity<List<StudentDTO>> searchStudents(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String college) {

        List<StudentDTO> students = studentFamilyServiceV2.searchByMultipleCriteria(
                keyword != null ? keyword : "",
                gender != null ? gender : "",
                major != null ? major : "",
                grade != null ? grade : "",
                college != null ? college : "");
        return ResponseEntity.ok(students);
    }

    // 创建学生信息
    @PostMapping
    public ResponseEntity<StudentDTO> createStudent(@RequestBody StudentDTO studentDTO) {
        try {
            StudentDTO createdStudent = studentFamilyServiceV2.saveStudentAndUpdateFamilyMessages(studentDTO.convertToEntity());
            return ResponseEntity.ok(createdStudent);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 更新学生信息
    @PutMapping("/{id}")
    public ResponseEntity<StudentDTO> updateStudent(@PathVariable UUID id, @RequestBody StudentDTO studentDTO) {
        Optional<StudentDTO> updatedStudent = studentFamilyServiceV2.findById(id).map(existingStudent -> {
            existingStudent.setAddress(studentDTO.getAddress());
            existingStudent.setBirthDate(Date.from(studentDTO.getBirthDate().atStartOfDay(ZoneId.systemDefault()).toInstant()));
            existingStudent.setName(studentDTO.getName());
            existingStudent.setNumber(studentDTO.getNumber());
            existingStudent.setPhone(studentDTO.getPhone());
            existingStudent.setGender(studentDTO.getGender());
            existingStudent.setMajor(studentDTO.getMajor());
            existingStudent.setGrade(studentDTO.getGrade());
            existingStudent.setCollege(studentDTO.getCollege());
            return studentFamilyServiceV2.saveStudentAndUpdateFamilyMessages(existingStudent.convertToEntity());
        });

        return updatedStudent.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 删除学生信息
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable UUID id) {
        studentFamilyServiceV2.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}